package com.gohi.main.wxapi.action;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.gohi.core.web.action.BaseAction;

import com.gohi.main.system.service.ISystemService;
import com.gohi.main.user.hbm.ShopgooWxMember;
import com.gohi.main.user.service.IShopgooWxMemberService;
import com.gohi.main.user.service.IUserService;
import com.gohi.main.util.EmojiFilter;
import com.gohi.main.util.Utils;
import com.gohi.main.wxapi.process.WxApi;
import com.gohi.main.wxapi.util.AccoutUtil;
import com.gohi.main.wxapi.vo.WxAccount;
import com.gohi.main.wxpay.api.WxPayUtil;

/**
 * 微信网页认证授权的
 * @author Administrator
 *
 */
public class OauthAction extends BaseAction {
	Logger logger = Logger.getLogger(OauthAction.class);
	private String  id;
	private String url;
	private IShopgooWxMemberService shopgooWxMemberService;
	// 用户
	private IUserService userService;

	@SuppressWarnings("deprecation")
	public String oauth() throws IOException {
			String u =	java.net.URLDecoder.decode("http://"+WxPayUtil.WXJSHost+"/oauth!index.do","GB2312");
			String type = this.getRequest().getParameter("type");//获取类型 
			 if(Utils.show(type).equals("")){
				 url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WxPayUtil.WX_APPID+"&redirect_uri="+u+"&response_type=code&scope=snsapi_userinfo&state=base&connect_redirect=1#wechat_redirect";
			 }else{
				 url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WxPayUtil.WX_APPID+"&redirect_uri="+u+"&response_type=code&scope=snsapi_userinfo&state=info&connect_redirect=1#wechat_redirect";
			 }
	   
		this.getRequest().setAttribute("url", url);
		//System.err.println(url);
		this.getResponse().getWriter().print("<script type='text/javascript'>window.location.href='"+url+"'</script>");
		return null;
	}
	
	 public String index() throws IOException{
		 HttpServletRequest request = this.getRequest();//
			String code=this.getRequest().getParameter("code");
			if(code!=null && !code.equals("")){
				//开始请求 表示授权成功
				String urls = WxApi.getFenCode(WxPayUtil.WX_APPID, WxPayUtil.WXAppSecret,code);
				JSONObject jsonObject = WxApi.httpsRequest(urls, "GET", null);
				//获取openid完毕 开始获取详细信息
				//System.err.println(jsonObject.toString());
			   //System.err.println(jsonObject.getString("access_token"));
				if(jsonObject==null){
					logger.error("微信参数空指针错误");
					return "ERROR";
				}
				if(jsonObject.containsKey("access_token")==false){
					logger.error("微信参数错误");
					return "ERROR";
				}
				//System.err.println("获取到:"+jsonObject.toString());
				if(jsonObject==null || jsonObject.containsKey("openid")==false){
					logger.info("授权参数错误！");
					return "oauthtz";
				}
				id=jsonObject.getString("openid");
				ShopgooWxMember fs=shopgooWxMemberService.getById(id);//跑到数据库里查询 一次 判断他是不是已经关注
				if(fs==null){
					urls=WxApi.getFenWeb(jsonObject.getString("access_token"), jsonObject.getString("openid"));
					jsonObject=WxApi.httpsRequest(urls, "GET", null);
				//	System.err.println(jsonObject.toString());
					ShopgooWxMember mem =new ShopgooWxMember();
					mem.setId(jsonObject.get("openid").toString());
					//mem.setNickname(EmojiFilter.filterEmoji(jsonObject.get("nickname").toString()));
					mem.setNickname(" ");
					mem.setHeadimg(jsonObject.get("headimgurl").toString());
					shopgooWxMemberService.saveOrUpdate(mem);
					//wxFensiService.saveOrUpdate(f);	//插入一条数据
					//System.err.println("成功插入一条授权粉丝，未关注："+f.getNickname());
					// System.err.println("插入成功:"+id);
				}else{
					if(!Utils.show(fs.getRealid()).equals("")){
						this.getRequest().getSession().setAttribute("user", userService.getById(fs.getRealid())); 
					}

				}

			  
			    this.getRequest().getSession().setAttribute("openid", id);
			    
	
			    
			}
			
		//	System.err.println(id);
			return "oauthtz";
	  }
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}

	public IShopgooWxMemberService getShopgooWxMemberService() {
		return shopgooWxMemberService;
	}

	public void setShopgooWxMemberService(
			IShopgooWxMemberService shopgooWxMemberService) {
		this.shopgooWxMemberService = shopgooWxMemberService;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	
	
}
